# Create your views here.
# -*- coding: utf-8 -*-
from django.views.generic.list_detail import object_list, object_detail
from wal.articulos.models import Articulo, AEntrada, ASalida, AStock, Ensamblado, Partes
from wal.articulos.forms import ArticulosForm, AEntradasForm, ASalidasForm, EnsambladosForm, PartesForm
from wal.familias.models import Familia
from wal.pedidos.forms import SearchForm
from django.template.context import RequestContext
from django.shortcuts import render_to_response
#from wal.views import update_object, create_object , delete_object
from django.views.generic.create_update import update_object, create_object , delete_object
from django.core.exceptions import ObjectDoesNotExist
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
from wal.views import split_query_into_keywords
from django.db.models import Q

def obtenerArticulo(request,object_id):
    if int(object_id):
        try:
            objectoArticulo = Articulo.objects.get(id=object_id)
        except ObjectDoesNotExist:
            return 'No existe el objecto'
    else:
        return 'No existe el objecto'
    return objectoArticulo

def listar(request,ot,o,page):
    
    request.breadcrumbs([('Depósito','/wal/dep'),('Artículos',request.path)])
    
    if ot=='asc':
        if int(o) == 1:
            orden = "-nombre"
        elif int(o) == 2:
            orden = "-familia"
        elif int(o) == 3:
            orden = "-subfamilia"
        elif int(o) == 4:
            orden = "-descripcion"
        else:
            orden = "-nombre"
    elif ot=='desc':
        if int(o) == 1:
            orden = "nombre"
        elif int(o) == 2:
            orden = "familia"
        elif int(o) == 3:
            orden = "subfamilia"
        elif int(o) == 4:
            orden = "descripcion"
        else:
            orden = "nombre"
    else:
        orden = "-nombre"
    if request.method == 'GET':
        form = SearchForm(request.GET)
        if form.is_valid():
            keywords = form.cleaned_data['keywords']
            keyword_list = split_query_into_keywords(keywords)
            articulos = search_for_keywords(keyword_list)
            if articulos:
                # Show the results
                qs = articulos.order_by(orden)
            else:
                qs = Articulo.objects.none()
            form = SearchForm()
            return object_list(request,
                   queryset = qs,
                   allow_empty = True,
                   template_name = 'articulos/listar.html',
                   extra_context = {'ot':ot,'o':o,'page':page,'form':form},
                   paginate_by = 20,
                   page = page,
                   )
    else:
        form = SearchForm()
    return object_list(request,
                   queryset = Articulo.objects.order_by(orden),
                   allow_empty = True,
                   template_name = 'articulos/listar.html',
                   extra_context = {'ot':ot,'o':o,'page':page,'form':form},
                   paginate_by = 20,
                   page = page,
                   )
    
def ver(request, object_id):
    articulo = obtenerArticulo(request, object_id)
    
    request.breadcrumbs([('Depósito','/wal/dep'),('Artículos',reverse(listar,args=['asc',1,1])),(articulo.nombre,request.path)])
    
    if articulo == 'No existe el objecto':
        return render_to_response('error.html',{'error':'No existe el objecto'})
    return render_to_response('articulos/detalles.html', {'articulo': articulo}, context_instance=RequestContext(request))

def crear(request):
#    if request.method == "POST":
#        pform = ArticulosForm(request.POST, instance=Articulo())
#        if pform.is_valid():
#            new_articulo = pform.save()
#            return HttpResponseRedirect(reverse(ver, args=[new_articulo.id]))
#    else:
#        pform = ArticulosForm(instance=Articulo())
#    return render_to_response('articulos/articulo.html', {'form': pform}, context_instance=RequestContext(request))
    request.breadcrumbs([('Artículos',reverse(listar,args=['asc',1,1])),('Crear Artículo',request.path)])
    return create_object(request,
                         model = Articulo, 
                         form_class = ArticulosForm,
                         template_name = 'articulos/articulo.html', 
                         post_save_redirect = '/wal/articulos/listar/ot=asc&o=1&page=1'
                         )

def editar(request, object_id):
    articulo = obtenerArticulo(request, object_id)
    if articulo == 'No existe el objecto':
        return render_to_response('error.html',{'error':'No existe el objecto'})

    request.breadcrumbs([('Depósito','/wal/dep'),('Artículos',reverse(listar,args=['asc',1,1])),('Editar '+articulo.nombre,request.path)])

    return update_object(request,
                        model = Articulo, 
                        #form_class = PedidosForm,
                        template_name = 'articulos/articulo.html', 
                        post_save_redirect = reverse(ver,args=[object_id]),
                        object_id = object_id
                        )
    
def borrar(request, object_id,ot,o,page):
    articulo = obtenerArticulo(request, object_id)
    if articulo == 'No existe el objecto':
        return render_to_response('error.html',{'error':'No existe el objecto'})
    return delete_object(request,
                         model = Articulo, 
                         template_name = 'articulos/confirm_delete_articulo.html', 
                         post_delete_redirect = reverse(listar, args=[ot,o,page]),
                         object_id = object_id
                         )
    
def search_for_keywords(keywords):
    """Make a search that contains all of the keywords."""
    articulos = Articulo.objects.all()
    for keyword in keywords:
        articulos = articulos.filter(
                                     Q(nombre__icontains=keyword)|
                                     Q(familia__nombre__icontains=keyword)|
                                     Q(subfamilia__nombre__icontains=keyword)|
                                     Q(descripcion__icontains=keyword))
    return articulos

def obtenerEntrada(request,object_id):
    if int(object_id):
        try:
            objectoEntrada = AEntrada.objects.get(id=object_id)
        except ObjectDoesNotExist:
            return 'No existe el objecto'
    else:
        return 'No existe el objecto'
    return objectoEntrada

def search_for_keywords_entradas(keywords):
    """Make a search that contains all of the keywords."""
    entradas = AEntrada.objects.all()
    for keyword in keywords:
        entradas = entradas.filter(
                                     Q(fecha__icontains=keyword)|
                                     Q(articulo__nombre__icontains=keyword))
    return entradas

def listarEntradas(request,ot,o,page):
    
    request.breadcrumbs([('Depósito','/wal/dep'),('Entradas de Artículos',request.path)])
    
    if ot=='asc':
        if int(o) == 1:
            orden = "-fecha"
        elif int(o) == 2:
            orden = "-articulo"
        else:
            orden = "-fecha"
    elif ot=='desc':
        if int(o) == 1:
            orden = "fecha"
        elif int(o) == 2:
            orden = "articulo"
        else:
            orden = "fecha"
    else:
        orden = "-fecha"
    if request.method == 'GET':
        form = SearchForm(request.GET)
        if form.is_valid():
            keywords = form.cleaned_data['keywords']
            keyword_list = split_query_into_keywords(keywords)
            entradas = search_for_keywords_entradas(keyword_list)
            if entradas:
                # Show the results
                qs = entradas.order_by(orden)
            else:
                qs = AEntrada.objects.none()
            form = SearchForm()
            return object_list(request,
                   queryset = qs,
                   allow_empty = True,
                   template_name = 'articulos/listarEntradas.html',
                   extra_context = {'ot':ot,'o':o,'page':page,'form':form},
                   paginate_by = 20,
                   page = page,
                   )
    else:
        form = SearchForm()
    return object_list(request,
                   queryset = AEntrada.objects.order_by(orden),
                   allow_empty = True,
                   template_name = 'articulos/listarEntradas.html',
                   extra_context = {'ot':ot,'o':o,'page':page,'form':form},
                   paginate_by = 20,
                   page = page,
                   )

def crearEntrada(request):
    request.breadcrumbs([('Depósito','/wal/dep'),('Entradas de Artículos',reverse(listarEntradas,args=['asc',1,1])),('Agregar Entrada de Artículo',request.path)])
    if request.method == "POST":
        cforms = AEntradasForm(request.POST, instance=AEntrada())
        if cforms.is_valid():
            new_entrada = cforms.save()
            
            stock = AStock.objects.filter(articulo=new_entrada.articulo)
            if stock:
                stock = AStock.objects.get(articulo=new_entrada.articulo)
                stock.stock = stock.stock + new_entrada.cantidad
                stock.save()
            else:
                new_stock = AStock(articulo=new_entrada.articulo,stock=new_entrada.cantidad)
                new_stock.save()
        return HttpResponseRedirect('/wal/articulos/entradas/listar/ot=asc&o=1&page=1')
    else:
        cforms = AEntradasForm(instance=AEntrada())
    return render_to_response('articulos/entrada.html',{'form':cforms},context_instance=RequestContext(request))

    
def borrarEntrada(request, object_id,ot,o,page):
    entrada = obtenerEntrada(request, object_id)
    if entrada == 'No existe el objecto':
        return render_to_response('error.html',{'error':'No existe el objecto'})
    if request.method == "POST":
            stock = AStock.objects.filter(articulo=entrada.articulo)
            if stock:
                stock = AStock.objects.get(articulo=entrada.articulo)
                stock.stock = stock.stock - entrada.cantidad
                stock.save()
    return delete_object(request,
                         model = AEntrada, 
                         template_name = 'articulos/confirm_delete_entrada.html', 
                         post_delete_redirect = reverse(listarEntradas, args=[ot,o,page]),
                         object_id = object_id
                         )

def obtenerSalida(request,object_id):
    if int(object_id):
        try:
            objectoSalida = ASalida.objects.get(id=object_id)
        except ObjectDoesNotExist:
            return 'No existe el objecto'
    else:
        return 'No existe el objecto'
    return objectoSalida

def search_for_keywords_salidas(keywords):
    """Make a search that contains all of the keywords."""
    salidas = ASalida.objects.all()
    for keyword in keywords:
        salidas = salidas.filter(
                                     Q(fecha__icontains=keyword)|
                                     Q(articulo__nombre__icontains=keyword))
    return salidas

def listarSalidas(request,ot,o,page):
    
    request.breadcrumbs([('Depósito','/wal/dep'),('Salidas de Artículos',request.path)])
    
    if ot=='asc':
        if int(o) == 1:
            orden = "-fecha"
        elif int(o) == 2:
            orden = "-articulo"
        else:
            orden = "-fecha"
    elif ot=='desc':
        if int(o) == 1:
            orden = "fecha"
        elif int(o) == 2:
            orden = "articulo"
        else:
            orden = "fecha"
    else:
        orden = "-fecha"
    if request.method == 'GET':
        form = SearchForm(request.GET)
        if form.is_valid():
            keywords = form.cleaned_data['keywords']
            keyword_list = split_query_into_keywords(keywords)
            salidas = search_for_keywords_salidas(keyword_list)
            if salidas:
                # Show the results
                qs = salidas.order_by(orden)
            else:
                qs = ASalida.objects.none()
            form = SearchForm()
            return object_list(request,
                   queryset = qs,
                   allow_empty = True,
                   template_name = 'articulos/listarSalidas.html',
                   extra_context = {'ot':ot,'o':o,'page':page,'form':form},
                   paginate_by = 20,
                   page = page,
                   )
    else:
        form = SearchForm()
    return object_list(request,
                   queryset = ASalida.objects.order_by(orden),
                   allow_empty = True,
                   template_name = 'articulos/listarSalidas.html',
                   extra_context = {'ot':ot,'o':o,'page':page,'form':form},
                   paginate_by = 20,
                   page = page,
                   )

def crearSalida(request):
    request.breadcrumbs([('Depósito','/wal/dep'),('Salidas de Artículos',reverse(listarEntradas,args=['asc',1,1])),('Agregar Salida de Artículo',request.path)])
    if request.method == "POST":
        cforms = ASalidasForm(request.POST, instance=ASalida())
        if cforms.is_valid():
            new_salida = cforms.save(commit=False)
            
            stock = AStock.objects.filter(articulo=new_salida.articulo)
            if stock:
                stock = AStock.objects.get(articulo=new_salida.articulo)
                if new_salida.cantidad > stock.stock:
                    cleaned_data = super(ASalidasForm, cforms).clean()
                    cant = cleaned_data.get("cantidad")
                    #raise forms.ValidationError("Las Fechas están mal!")
                    msg = u"La Cantidad está mal!"
                    cforms._errors["cantidad"] = cforms.error_class([msg])
            
                    # These fields are no longer valid. Remove them from the
                    # cleaned data.
                    del cleaned_data["cantidad"]
                else:
                    stock.stock = stock.stock - new_salida.cantidad
                    stock.save()
                    new_salida.save()
                    return HttpResponseRedirect('/wal/articulos/salidas/listar/ot=asc&o=1&page=1')
    else:
        cforms = ASalidasForm(instance=ASalida())
    return render_to_response('articulos/salida.html',{'form':cforms}, context_instance=RequestContext(request))

def borrarSalida(request, object_id,ot,o,page):
    salida = obtenerSalida(request, object_id)
    if salida == 'No existe el objecto':
        return render_to_response('error.html',{'error':'No existe el objecto'})
    if request.method == "POST":
            stock = AStock.objects.filter(articulo=salida.articulo)
            if stock:
                stock = AStock.objects.get(articulo=salida.articulo)
                stock.stock = stock.stock + salida.cantidad
                stock.save()
    return delete_object(request,
                         model = ASalida, 
                         template_name = 'articulos/confirm_delete_salida.html', 
                         post_delete_redirect = reverse(listarSalidas, args=[ot,o,page]),
                         object_id = object_id
                         )
    
def search_for_keywords_stock(keywords):
    """Make a search that contains all of the keywords."""
    articulos = AStock.objects.all()
    for keyword in keywords:
        articulos = articulos.filter(
                                     Q(articulo__nombre__icontains=keyword)|
                                     Q(articulo__familia__nombre__icontains=keyword)|
                                     Q(articulo__subfamilia__nombre__icontains=keyword)|
                                     Q(articulo__descripcion__icontains=keyword))
    return articulos
    
def verStock(request,ot,o,page):
    request.breadcrumbs([('Depósito','/wal/dep'),('Stock de Artículos',request.path)])
    
    if ot=='asc':
            orden = "-articulo"
    else:
            orden = "articulo"
    if request.method == 'GET':
        form = SearchForm(request.GET)
        if form.is_valid():
            keywords = form.cleaned_data['keywords']
            keyword_list = split_query_into_keywords(keywords)
            stock = search_for_keywords_stock(keyword_list)
            if stock:
                # Show the results
                qs = stock.order_by(orden)
            else:
                qs = AStock.objects.none()
            form = SearchForm()
            return object_list(request,
                   queryset = qs,
                   allow_empty = True,
                   template_name = 'articulos/stock.html',
                   extra_context = {'ot':ot,'o':o,'page':page,'form':form},
                   paginate_by = 20,
                   page = page,
                   )
    else:
        form = SearchForm()
    return object_list(request,
                   queryset = AStock.objects.order_by(orden),
                   allow_empty = True,
                   template_name = 'articulos/stock.html',
                   extra_context = {'ot':ot,'o':o,'page':page,'form':form},
                   paginate_by = 20,
                   page = page,
                   )

def obtenerEnsamblado(request,object_id):
    if int(object_id):
        try:
            objectoEnsamblado = Ensamblado.objects.get(id=object_id)
        except ObjectDoesNotExist:
            return 'No existe el objecto'
    else:
        return 'No existe el objecto'
    return objectoEnsamblado

def obtenerParte(request,object_id):
    if int(object_id):
        try:
            objectoParte = Partes.objects.get(id=object_id)
        except ObjectDoesNotExist:
            return 'No existe el objecto'
    else:
        return 'No existe el objecto'
    return objectoParte    
    
def search_for_keywords_ensamblados(keywords):
    """Make a search that contains all of the keywords."""
    ensamblados = Ensamblado.objects.all()
    for keyword in keywords:
        ensamblados = ensamblados.filter(
                                     Q(nombre__icontains=keyword)|
                                     Q(descripcion__icontains=keyword))
    return salidas
    
def listarEnsamblados(request,ot,o,page):
    
    
    request.breadcrumbs([('Depósito','/wal/dep'),('Ensamblados',request.path)])
    
    if ot=='asc':
            orden = "-nombre"
    elif ot=='desc':
            orden = "nombre"
    else:
        orden = "-nombre"
    if request.method == 'GET':
        form = SearchForm(request.GET)
        if form.is_valid():
            keywords = form.cleaned_data['keywords']
            keyword_list = split_query_into_keywords(keywords)
            ensamblados = search_for_keywords_ensamblados(keyword_list)
            if ensamblados:
                # Show the results
                qs = ensamblados.order_by(orden)
            else:
                qs = Ensamblado.objects.none()
            form = SearchForm()
            return object_list(request,
                   queryset = qs,
                   allow_empty = True,
                   template_name = 'articulos/listarEnsamblados.html',
                   extra_context = {'ot':ot,'o':o,'page':page,'form':form},
                   paginate_by = 20,
                   page = page,
                   )
    else:
        form = SearchForm()
    return object_list(request,
                       queryset = Ensamblado.objects.order_by(orden),
                       allow_empty = True,
                       template_name = 'articulos/listarEnsamblados.html',
                       extra_context = {'ot':ot,'o':o,'page':page,'form':form},
                       paginate_by = 20,
                       page = page,
                       )
#    return object_list(request,
#                       queryset = Expedicion.objects.filter(pedido=object_id).order_by("-fecha"),
#                       allow_empty = True,
#                       template_name = 'expedicion/listar.html'
#                       )
    
def verEnsamblados(request, object_id):
    ensamblado = obtenerEnsamblado(request, object_id)
    if ensamblado == 'No existe el objecto':
        return render_to_response('error.html',{'error':'No existe el objecto'})
    
    request.breadcrumbs([('Depósito','/wal/dep'),('Ensamblados',reverse(listarEnsamblados,args=['asc',1,1])),(ensamblado.nombre,request.path)])
    
    if request.method == "POST":
        cforms = PartesForm(request.POST, instance=Partes())
        
        if cforms.is_valid():
            
            new_parte = cforms.save(commit=False)
            new_parte.ensamblado = ensamblado
            
            new_parte.save()
            return HttpResponseRedirect(reverse(verEnsamblados, args=[object_id]))
    else:
        cforms = PartesForm(instance=Partes())
    partes = Partes.objects.filter(ensamblado=object_id)
    list = []
    for item in partes:
        list.append(item)
    return render_to_response('articulos/detallesEnsamblado.html', {'ensamblado': ensamblado, 'partes': list, 'detalle_forms': cforms}, context_instance=RequestContext(request))

def crearEnsamblados(request):
    
    request.breadcrumbs([('Depósito','/wal/dep'),('Ensamblados',reverse(listarEnsamblados,args=['asc',1,1])),('Crear Ensamblado',request.path)])
    
    if request.method == "POST":
        pform = EnsambladosForm(request.POST, instance=Ensamblado())
        if pform.is_valid():
            new_ensamblado = pform.save()
            familia = Familia.objects.filter(nombre__iexact='Ensamblados')
            if familia:
                familia = Familia.objects.get(nombre__iexact='Ensamblados')
            else:
                familia = Familia(nombre='Ensamblados')
                familia.save()
            new_articulo = Articulo(nombre=new_ensamblado.nombre,familia=familia)
            new_articulo.save()
            return HttpResponseRedirect(reverse(verEnsamblados, args=[new_ensamblado.id]))
    else:
        pform = EnsambladosForm(instance=Ensamblado())
    return render_to_response('articulos/ensamblado.html', {'form': pform}, context_instance=RequestContext(request))

def editarEnsamblados(request, object_id):
    ensamblado = obtenerEnsamblado(request, object_id)
    if ensamblado == 'No existe el objecto':
        return render_to_response('error.html',{'error':'No existe el objecto'})


    request.breadcrumbs([('Depósito','/wal/dep'),('Ensamblados',reverse(listarEnsamblados,args=['asc',1,1])),('Editar '+ensamblado.nombre,request.path)])

    return update_object(request,
                        model = Ensamblado, 
                        #form_class = PedidosForm,
                        template_name = 'articulos/ensamblado.html', 
                        post_save_redirect = '/wal/articulos/ensamblados/ver/'+str(object_id),
                        object_id = object_id,
                        form_class = EnsambladosForm
                        )
    
def borrarEnsamblados(request, object_id,ot,o,page):
    ensamblado = obtenerEnsamblado(request, object_id)
    if ensamblado == 'No existe el objecto':
        return render_to_response('error.html',{'error':'No existe el objecto'})
    return delete_object(request,
                         model = Ensamblado, 
                         template_name = 'articulos/confirm_delete_ensamblado.html', 
                         post_delete_redirect = reverse(listarEnsamblados, args=[ot,o,page]),
                         object_id = object_id
                         )
    
def borrarParte(request, object_id):
    parte = obtenerParte(request, object_id)
    if parte == 'No existe el objecto':
        return render_to_response('error.html',{'error':'No existe el objecto'})
    ensamblado = parte.ensamblado
    return delete_object(request,
                         model = Partes, 
                         template_name = 'articulos/confirm_delete_parte.html', 
                         post_delete_redirect = reverse(verEnsamblados, args=[ensamblado.id]),
                         object_id = object_id
                         )    
